<template>
	<eui-page-frame topHeight="260">
		<template #top> 
			<view class="content-img">
				<eui-navbar ref="EuiNavBar" title="配送收货" color="#000000" backgroundColor="#FFFFFF"
					:storeName="sUserStoreName" :storeId="sUserStore" :option="nbOption" @menuFunc="onClickMenuFunc"
					@onClickStore="clickStore">
				</eui-navbar>
				<view class="top-view">
					<eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码"
						leftIcon="icon-saoyisao" @confirm="searchConfirm" @leftIconClick="scanCode" radius="30"
						showFilter="true">

						<template v-slot:searchFields>
							<view class="search-fields">
								<view class="center">
									<eui-card-input class="search-field" v-model="formData.c_id" title="单据号"
										placeholder="请输入单据号" type="text" />
									<eui-card-input class="search-field" v-model="formData.c_out_adnoname" title="部门"
										placeholder="请选择" type="text" name="rdsDeparts" rightIconType="right"
										@iconClick="clickRight('depart')" :displayable="true" />
									<eui-card-input class="search-field" v-model="formData.c_d_status" title="收发货状态"
										type="radio" :range="getDictSelectList('收发货状态')" />
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_s" title="开始日期"
										placeholder="请选择开始日期" type="date" :displayable="false" rightIconType="clear" @iconClick="clear" singleTag="c_mk_dt_s"/>
									<eui-card-input class="search-field" v-model="formData.c_mk_dt_e" title="结束日期"
										placeholder="请选择结束日期" type="date" :displayable="false" rightIconType="clear" @iconClick="clear" singleTag="c_mk_dt_e"/>
									<eui-card-input class="search-field" v-model="formData.c_mk_username" title="制单人"
										placeholder="请选择制单人" type="text" name="rdsUsers" rightIconType="right"
										@iconClick="clickRight('user')" :displayable="true" />

								</view>
								<view class="bottom flex-1 flex">
									<eui-button type="max2" title="重置" singleTag="reset"
										@buttonClick="confirm"></eui-button>
									<eui-button type="max" title="确认" singleTag="fix"
										@buttonClick="confirm"></eui-button>
								</view>
							</view>
						</template>
					</eui-search-bar>
				</view>
			</view>
		</template>
		<!-- <eui-page-content> -->
			<view class="footer-view">
				<eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" isBottom="true"
					@itemClick="onClickGoToDetail" :origList="dataList"  type="list">
					<template v-slot:list="scope">
						<view class="status-view">
							<eui-status :type="scope.c_d_status=='0'?'primary_third':scope.c_d_status=='1'?'warning_third':'success_third'" :title="getDictName('收发货状态', scope.c_d_status)"></eui-status>
						</view>
					   <eui-text :value="scope.c_out_store_id" :name="getRelatedName('rdsStores', scope.c_out_store_id)"
						  type="titlename2" title="配送中心" occupy cWidth="width: 100%"/>
					   <eui-text :value="scope.c_out_adno" :name="getRelatedName('rdsDeparts', scope.c_out_adno)" type="titlename2"
									  title="部门" />
					   <eui-text :value="scope.c_out_wno" :name="getRelatedName('rdsWnos', scope.c_out_wno)" type="titlename2"
									  title="仓库"  />
					   <eui-text :value="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)"
						  type="titlename2" title="录入" />
					   <eui-text :value="scope.c_mk_dt" type="rdstime2" />
					   <eui-text :value="scope.c_out_au_userno" type="titlename2" title="审核"
						  :name="getRelatedName('rdsUsers', scope.c_out_au_userno)" v-if="scope.c_status == '3'" />
					   <eui-text :value="scope.c_out_au_dt" type="rdstime2" v-if="scope.c_status == '3'" />
					</template>
					<template v-slot:bottom="scope" v-if="scope?.c_status != '8' || scope?.c_approve_status != '3'">
						<view>
							<eui-button :modelValue="scope" :type="!setShowDetail(scope)?'min':'min2'" title="收货"
								v-if="scope?.c_status == '3' && scope?.c_d_status == '1' && ['0', '1', '2', '3'].includes(scope?.c_summary)"
								@buttonClick="buttonReceipt" />
						</view>
						<view>
							<eui-button :modelValue="scope" type="min" title="详情"
								v-if="setShowDetail(scope)" @buttonClick="buttonDetail"/>
						</view>
					</template>
				</eui-virtual-list>
			</view>
		<!-- </eui-page-content> -->
	</eui-page-frame>
</template>

<script setup type="ts">
	import { ref, reactive, onMounted } from 'vue';
	import {useMainStore} from "@/store/modules/store";
	import {useLoginStore} from "@/store/modules/useLoginStore";
	import { validateStores } from '@/hooks/useValidateMethod';
	import dateRangUtil from '../../../common/dateRangUtil';
	import { getRelatedName, getDictName,getDictSelectList, getDictSelect } from '../components/RelatedName.js';
	import Enjoy from "@/common/enjoy";
	import {onLoad} from "@dcloudio/uni-app";
	import { init } from '@/hooks/init';
	import useService from '@/hooks/useService';
	const service = useService({ prefix: "scApi" });
	
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const EuiNavBar = ref(null);
	const RdsSearchBar = ref(null);
	const searchText = ref('');
	const sUserStore = ref('');
	const sUserStoreName = ref('');
	const sUser = ref('');
	const nbOption = ref({
	  items: [
	    {title: '我要收货', onClick: 'onClickNewCount', icon: 'plusempty'},
	  ]
	})
	const displayable = ref(false);  //true允许页面编辑
	const formData = ref({
	   c_mk_dt_s: (dateRangUtil.getLast1Month())[0],
	   c_mk_dt_e: (dateRangUtil.getLast1Month())[2],
	   c_out_adno: '',
	   c_out_adnoname:'',
	   c_id: '',
	   c_status: '3',
	   c_d_status: '1', // 默认查询已发货的
	   c_mk_userno: '',
	   c_mk_username:''
	})
	const dataList = ref([]);
	const CurrentPage = ref(1);  //第几页
	const PageSize = ref(10);  //每页10条
	const RowsCount = ref(0);  //总条数
	const PageCount = ref(1);  //总页数
	const { loginInfo } = mainStore;
	// const dataOptions = ref([
	// 	{ label:'收发货状态', name:'c_d_status_name' },
	// 	{ label: "配送中心", name: "c_out_store_name" },
	// 	{ label: "部门", name: "c_out_adno_name" },
	// 	{ label: "仓库", name: "c_out_wno_name" },
	// 	{ label: "录入人", name: "c_mk_username" },
	// 	{ label: "录入时间", name: "c_mk_dt" },
	// 	{ label: "审核人", name: "c_out_au_username" },
	// 	{ label: "审核时间", name: "c_out_au_dt" },
	// ])
	
	onLoad(async () => {
	  await init();
	  if (!loginInfo.sUserStore) {
	    EuiNavBar.value.onClickStore();
	    return;
	  }
	  setDefault();
	  await getData();
	})
	const setShowDetail = (scope)=>{
		return  scope?.c_d_status == '3' && ['3', '8', '9'].includes(scope?.c_status)
	}
	const setDefault = () => {
		sUserStore.value = loginInfo.sUserStore;
		sUserStoreName.value = loginInfo.sUserStoreName;
		sUser.value = loginInfo.sUser;
	}
	const clear = (e)=>{
		switch (e) {
			case 'c_mk_dt_s':
			  formData.value.c_mk_dt_s = '';
			  break;
			case 'c_mk_dt_e':
			  formData.value.c_mk_dt_e = '';
			  break;
		}
	}
	const onClickNewCount =()=>{
		RdsNavBar.value.popup.close('bottom');
		uni.navigateTo({
			url: './edit?storeId=' + sUserStore.value
		});
	}
	// 上拉加载更多
	const templateLower = async() =>{
		if (CurrentPage.value < PageCount.value) {
			CurrentPage.value = CurrentPage.value + 1;
			await getData(true);
		}
    }
	const clickRight = (selectType) =>{
		uni.navigateTo({
		    url: `../modals/index?type=${selectType}`
		});
	}
	const SelectionChanged = (type, item) => {
		switch (type) {
			case 'user':
				formData.value.c_mk_userno = item.value;
				formData.value.c_mk_username = item.text;
				break;
			case 'depart':
				formData.value.c_out_adno = item.value;
				formData.value.c_out_adnoname = item.text;
				break;
		}
	}
	const searchConfirm = async (e) => {
	  if (!e) {
	    return;
	  }
	  searchText.value = e.value;
	  await getData();
	}
	// 点击扫描图标跳转打开摄像头
	const scanCode = () => {
	  uni.scanCode({
	    success: function (res) {
	      if (res.result != '' && res.result != undefined && res.result != null) {
	        searchText.value = res.result;
	         getData();
	      }
	    },
	  });
	}
	const confirm = async(t) => {
	  let { singleTag } = t;
	  switch (singleTag) {
	    case 'reset':
	       formData.value.c_mk_dt_s = (dateRangUtil.getLast1Month())[0];
	       formData.value.c_mk_dt_e = (dateRangUtil.getLast1Month())[2];
		   formData.value.c_out_adno = '';
		   formData.value.c_out_adnoname = '';
		   formData.value.c_id = '';
		   formData.value.c_status = '3';
		   formData.value.c_d_status = '1'; // 默认查询已发货的
		   formData.value.c_mk_userno = '';
		   formData.value.c_mk_username = '';
	      break;
	    case 'fix':
	      await getData();
	      // 关闭弹出层
	      RdsSearchBar.value.closeDrawer();
	      break;
	  }
	}
	// 新增单据
	const onClickMenuFunc = (e) => {
	  console.log('=====onClickMenuFunc: ', e);
	  switch (e) {
	    case 'onClickNewCount':
	      setTimeout(() => {
	        EuiNavBar.value.closeDrawer();
	      },1200);
	      uni.navigateTo({
	        url: './edit?storeId=' + sUserStore.value
	      });
	      break;
	  }
	}
	const onClickGoToDetail = (e) => {
		uni.navigateTo({
			url: './edit?c_id=' + e.item.c_id + '&storeId=' + sUserStore.value
		});
	}
	// 选择框点击事件
	const clickStore = () => {
	  let parms = Enjoy.GetDialogParms();
	  parms.CallBack = SelectionStoreChanged;
	  parms.SelectionType = "机构选择";
	  parms.SelectedItems = sUserStore.value;
	  Enjoy.OpenDialog(parms)
	}
	const SelectionStoreChanged = async (event) => {
	  if (event.SelectionType == '机构选择') {
	    // 更新机构信息
	    sUserStoreName.value = event.BackParms.Value;
	    sUserStore.value = event.BackParms.Key;
	  }
	  // 按新条件获取数据
	  await getData();
	}
	//判断是否包含英文
	const containsLetters = (str)=>{
		 return /[a-zA-Z]/.test(str);
	}
	const getData = async(e) =>{
		if (!e) {
			CurrentPage.value = 1;
		}				
		const req = {
			IsNotPage: false,
			CurrentPage: CurrentPage.value,
			PageSize: PageSize.value,
			UserNo: loginInfo.sUser,
			WhereList: [
				{ c_col: "c_in_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
				{ c_col: "c_mk_dt", c_oper: "大于等于", c_value: formData.value.c_mk_dt_s, c_logic: "而且", c_col_dtype: "System.DateTime" },
				{ c_col: "c_mk_dt", c_oper: "小于等于", c_value: formData.value.c_mk_dt_e, c_logic: "而且", c_col_dtype: "System.DateTime" },
				formData.value.c_out_adno ? { c_col: "c_out_adno", c_oper: "等于", c_value: formData.value.c_out_adno, c_logic: "而且" } : {},
				formData.value.c_id ? { c_col: "c_id", c_oper: "等于", c_value: formData.value.c_id, c_logic: "而且" } : {},
				{ c_col: "c_status", c_oper: "等于", c_value: formData.value.c_status, c_logic: "而且" },
				{ c_col: "c_d_status", c_oper: "等于", c_value: formData.value.c_d_status, c_logic: "而且" },
				formData.value.c_mk_userno ? { c_col: "c_mk_userno", c_oper: "等于", c_value: formData.value.c_mk_userno, c_logic: "而且" } : {},
			]
		}

		if (searchText.value) {
			let strlength = searchText.value.length;
			//判断是否包含英文
			const falg = containsLetters(searchText.value);
			if (!falg) {
				strlength = 7;
			}
			switch (strlength) {
				case 7: //商品编码
					req.WhereList.push({
						c_col: "c_gcode",
						c_oper: "等于",
						c_value: searchText.value,
						c_logic: "而且",
					});
					break;
				case 13://订单号
					req.WhereList.push({
						c_col: "c_id",
						c_oper: "等于",
						c_value: searchText.value,
						c_logic: "而且",
					});
					break;
				default:
					req.WhereList.push({
						c_col: "c_gcode",
						c_oper: "等于",
						c_value: searchText.value,
						c_logic: "而且",
					});
					break;
			}
		}
		uni.showLoading({ title: "正在加载...", mask: true })
		const result = await service.request('商品配送单', 'EnjoyQueryList', req,'801');
		uni.hideLoading();
		CurrentPage.value = result.CurrentPage; //第几页
		PageSize.value = result.PageSize; //每页10条
		RowsCount.value = result.RowsCount; //总条数
		PageCount.value = result.PageCount; //总页数
		if (result.CurrentPage == 1) {
			dataList.value = result.ReturnObject;
			// dataList.value = result.ReturnObject.map(x=>{
			// 	return {
			// 		...x,
			// 		c_out_store_name:x.c_out_store_id?'['+x.c_out_store_id+']'+getRelatedName('rdsStores', x.c_out_store_id):'',
			// 		c_out_adno_name:x.c_out_adno?'['+x.c_out_adno+']'+getRelatedName('rdsDeparts', x.c_out_adno):'',
			// 		c_out_wno_name:x.c_out_wno?'['+x.c_out_wno+']'+getRelatedName('rdsWnos', x.c_out_wno):'',
			// 		c_mk_username:x.c_mk_userno?'['+x.c_mk_userno+']'+getRelatedName('rdsUsers', x.c_mk_userno):'',
			// 		c_out_au_username:x.c_out_au_userno?'['+x.c_out_au_userno+']'+getRelatedName('rdsUsers', x.c_out_au_userno):'',
			// 		c_d_status_name:getDictName('收发货状态', x.c_d_status),
			// 		c_mk_dt: dayjs(x.c_mk_dt).format('YYYY-MM-DD HH:mm:ss'),
			// 		c_out_au_dt: x.c_out_au_dt?dayjs(x.c_out_au_dt).format('YYYY-MM-DD HH:mm:ss'):''
			// 	}
			// });
		} else {
			dataList.value = dataList.value.concat(result.ReturnObject);
		}
		
	}
	//收货
	const buttonReceipt = async(e)=>{
		const item = e.modelValue;
		 if (item.c_status == '3') 
		 {
			uni.navigateTo({
				url: './edit?c_id=' + item.c_id + '&storeId=' + sUserStore.value
			});
		}
	}
	//详情
	const buttonDetail = async(e)=>{
		const item = e.modelValue;
		 uni.navigateTo(
			{
				url: './edit?c_id=' + item.c_id + '&storeId=' + sUserStore.value
			}
		);
	}
	defineExpose({
		SelectionChanged
	})
</script>

<style lang="scss" scoped>
	@import '../../../main.scss';
	.content {
		display: flex;
		flex: 1;
		flex-direction: column;
		background-color: #F2F2F2;
		padding: 0px !important
	}

	.content-img {
		background-color: #FFFFFF;
		background-size: 100% 176rpx;
		background-repeat: no-repeat;
		width: 100%;
	}

	.navigation {
		flex: 0 0 auto;
		margin-bottom: 5px;
	}
	.top-view {
		width: 100%;
		height: 88rpx;
		background: #FFFFFF;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
	}

	.search-fields {
		width: 100%;
		background: #FFFFFF;
		position: relative;

		.bottom {
			background: #ffffff;
			border-top: 1rpx solid $uni-line-color;
			display: flex;
			justify-content: center;
			padding: 20rpx;
		}
	}
	.status-view{
		width: 100%;
		text-align: right;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	.footer-view{
		height:100%;
		background: $uni-bg-color;
	}
	::v-deep .white-main{
		left:0;
		right:0;
	}
	::v-deep .item-detail-view{
		margin: 4rpx 0px;
	}
</style>